import { defineStore } from 'pinia'

const userInfoRaw = () => ({
  _id: '',
  token: '',
  username: '',
  role: [],
  nickname: '',
  department: '',
  position: ''
})
const userInfo = localStorage.getItem('userInfo')
  ? JSON.parse(localStorage.getItem('userInfo'))
  : userInfoRaw()

export const useUserStore = defineStore({
  id: 'user',
  state: () => Object.assign({}, userInfo),
  actions: {
    login(data) {
      Object.assign(this, data)

      localStorage.setItem('userInfo', JSON.stringify(data))
    },
    logout() {
      Object.assign(this, userInfoRaw())

      localStorage.removeItem('userInfo')
    }
  }
})
